-------------------------------------------------------------------------------
---! 内部方法
-------------------------------------------------------------------------------
---! 查找副本配置
local function find_dungeon_configs(dungeon_level)
    local configs = IMPORT_D:query("dungeon")
    if not configs then
        return
    end

    local config = configs[dungeon_level]
    if not config then
        return
    end

    return config
end

-------------------------------------------------------------------------------
---! 对外接口
-------------------------------------------------------------------------------
DUNGEON_D = {}

function DUNGEON_D:get_dungeon_times(player, difficult)
    return player:query("dungeon", difficult, "times") or 0
end

function DUNGEON_D:start_dungeon(player, difficult)
    ---! 获取当前玩家最大等级
    local level = player:get_level()

    ---! 获取对应副本的配置
    local configs = find_dungeon_configs(level)
    if not configs then
        ---! 副本配置不存在
        local result = {}
        result.error = 1
        player:send_packet("MSGS2CDungeonStart", result)
        return
    end

    ---! 获取对应难度的配置
    local config = configs[difficult]
    if not config then
        ---! 难度配置不存在
        local result = {}
        result.error = 2
        player:send_packet("MSGS2CDungeonStart", result)
        return
    end

    if level < config.unlock then
        ---! 指定关卡未解锁
        local result = {}
        result.error = 3
        player:send_packet("MSGS2CDungeonStart", result)
        return
    end

    local times = DUNGEON_D:get_dungeon_times(player, difficult)
    if times >= config.dailyNum then
        ---! 挑战次数已用完
        local result = {}
        result.error = 4
        player:send_packet("MSGS2CDungeonStart", result)
        return
    end

    ---! todo: 开始副本

    local result = {}
    result.error = 0
    result.id = config.id
    player:send_packet("MSGS2CDungeonStart", result)
end

function DUNGEON_D:kill_monster(player, monster_id)
end

function DUNGEON_D:send_dungeon_info(player)
    ---! 获取当前玩家最大等级
    local level = player:get_level()

    ---! 获取对应副本的配置
    local configs = find_dungeon_configs(level)
    if not configs then
        return
    end

    local dungeons = {}
    for _, config in pairs(configs) do
        local dungeon = {}
        dungeon.difficult = config.difficult
        dungeon.times = math.max(0, config.dailyNum - DUNGEON_D:get_dungeon_times(player, config.difficult))
        table.insert(dungeons, dungeon)
    end

    local result = {}
    result.dungeons = dungeons
    player:send_packet("MSGS2CDungeonInfo", result)
end
